package com.example.airoles.controller;

import com.example.airoles.config.RoleConfig;
import com.example.airoles.dto.*;
import com.example.airoles.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class ChatController {

    @Autowired
    private LlmService llmService;

    @Autowired
    private RoleConfig roleConfig;
    
    @Autowired
    private ConversationSessionService sessionService;
    
    @Autowired
    private RoleRecommendationService recommendationService;
    
    // Keep the original ChatResponse class for backwards compatibility
    public static class ChatResponse {
        public String assistant;
    }

    @PostMapping("/chat")
    public ChatResponse chat(@RequestBody ChatRequest req) {
        String system = roleConfig.roleSystemPrompts.getOrDefault(req.roleId, "你是一个虚拟角色。");
        String skillFragment = roleConfig.skillFragments.getOrDefault(req.skill, "");
        return llmService.chatWithRole(system, skillFragment, req.conversation);
    }
    
    @PostMapping("/chat/enhanced")
    public EnhancedChatResponse chatEnhanced(@RequestBody EnhancedChatRequest req) {
        // Get or create session
        ConversationSession session = sessionService.getOrCreateSession(
            req.sessionId, req.userId, req.roleId, req.skill);
        
        // Add user message to session
        if (req.conversation != null && !req.conversation.isEmpty()) {
            ChatRequest.Message lastMessage = req.conversation.get(req.conversation.size() - 1);
            session.addMessage(lastMessage);
        }
        
        // Build system prompt with context
        String systemPrompt = buildContextualSystemPrompt(req, session);
        String skillFragment = roleConfig.skillFragments.getOrDefault(req.skill, "");
        
        // Get LLM response
        ChatResponse basicResponse = llmService.chatWithRole(systemPrompt, skillFragment, session.messages);
        
        // Create enhanced response
        EnhancedChatResponse response = new EnhancedChatResponse();
        response.sessionId = session.sessionId;
        response.assistant = basicResponse.assistant;
        response.metadata = new EnhancedChatResponse.ResponseMetadata();
        response.insights = generateInsights(session, req);
        
        // Add assistant message to session
        ChatRequest.Message assistantMessage = new ChatRequest.Message();
        assistantMessage.role = "assistant";
        assistantMessage.text = response.assistant;
        session.addMessage(assistantMessage);
        
        // Generate follow-up questions based on skill
        response.followUpQuestions = generateFollowUpQuestions(req.skill, response.assistant);
        
        return response;
    }
    
    @GetMapping("/roles/search")
    public List<RoleRecommendationService.RoleInfo> searchRoles(@RequestParam String query) {
        return recommendationService.searchRoles(query);
    }
    
    @GetMapping("/roles/category/{category}")
    public List<RoleRecommendationService.RoleInfo> getRolesByCategory(@PathVariable String category) {
        return recommendationService.getRolesByCategory(category);
    }
    
    @PostMapping("/roles/recommend")
    public RoleRecommendationService.RoleRecommendation recommendRole(@RequestBody Map<String, String> request) {
        String userMessage = request.getOrDefault("message", "");
        return recommendationService.recommendRole(userMessage);
    }
    
    @GetMapping("/sessions/{userId}")
    public List<ConversationSession> getUserSessions(@PathVariable String userId) {
        return sessionService.getRecentSessions(userId, 10);
    }
    
    @GetMapping("/roles")
    public Map<String, String> getAllRoles() {
        return roleConfig.roleSystemPrompts;
    }
    
    @GetMapping("/skills")
    public Map<String, String> getAllSkills() {
        return roleConfig.skillFragments;
    }
    
    private String buildContextualSystemPrompt(EnhancedChatRequest req, ConversationSession session) {
        String basePrompt = roleConfig.roleSystemPrompts.getOrDefault(req.roleId, "你是一个虚拟角色。");
        
        StringBuilder contextualPrompt = new StringBuilder(basePrompt);
        
        // Add emotional context if provided
        if (req.emotionalContext != null) {
            contextualPrompt.append("\n\n当前用户情绪状态: ");
            if (req.emotionalContext.currentMood != null) {
                contextualPrompt.append("心情: ").append(req.emotionalContext.currentMood).append("; ");
            }
            if (req.emotionalContext.stressLevel > 0) {
                contextualPrompt.append("压力等级: ").append(req.emotionalContext.stressLevel).append("/10; ");
            }
            if (req.emotionalContext.supportType != null) {
                contextualPrompt.append("需要的支持类型: ").append(req.emotionalContext.supportType);
            }
        }
        
        return contextualPrompt.toString();
    }
    
    private EnhancedChatResponse.ConversationInsights generateInsights(ConversationSession session, EnhancedChatRequest req) {
        EnhancedChatResponse.ConversationInsights insights = new EnhancedChatResponse.ConversationInsights();
        
        // Simple emotion detection based on keywords
        if (req.conversation != null && !req.conversation.isEmpty()) {
            String lastUserMessage = req.conversation.get(req.conversation.size() - 1).text.toLowerCase();
            insights.detectedEmotion = detectEmotion(lastUserMessage);
        }
        
        insights.progressNotes = "对话进行中，继续探索用户需求";
        insights.suggestedNextSkill = "perspective_shift";
        
        return insights;
    }
    
    private String detectEmotion(String message) {
        if (message.contains("伤心") || message.contains("难过")) {
            return "sadness";
        } else if (message.contains("焦虑") || message.contains("担心")) {
            return "anxiety";
        }
        return "neutral";
    }
    
    private List<String> generateFollowUpQuestions(String skill, String response) {
        return List.of(
            "你还想进一步探讨什么？",
            "这个回答对你有帮助吗？"
        );
    }
}
